package controller;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletContext;

public class DBmanager {
	
	private static DBmanager uniqueInstance=null;
	
	private Connection con = null ;
	private String driver = "";
	private String dbname = "";
        
	
	private DBmanager(ServletContext context){
		driver = context.getInitParameter("db_driver");
		dbname = context.getInitParameter("db_url");
		if(!dbExists(dbname))
		{
			System.err.println("de database bestaat niet, database aanmaken...");	
			if(dbExists(dbname + ";create=true")){
				try {
					Statement s = con.createStatement();
					s.executeUpdate("CREATE TABLE USERS (userID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), PRIMARY KEY (userID), username varchar(64), password varchar(64))");
					s.executeUpdate("CREATE TABLE AUCTIONS (auctionID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), PRIMARY KEY (auctionID), title varchar(128), pic varchar(64), details varchar(512), owner INT, price DECIMAL(18,2), dend TIMESTAMP)");
					s.executeUpdate("CREATE TABLE BIDS (bidID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), PRIMARY KEY (bidID), auction INT, bidder INT, bid DECIMAL(18,2), bdate TIMESTAMP)");
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static synchronized DBmanager getInstance(ServletContext context) {
		if (uniqueInstance==null) {
			uniqueInstance = new DBmanager(context);
		}
		return uniqueInstance;
	}
	
	public static synchronized DBmanager getInstance() {
		if (uniqueInstance==null) {
			return null; //dit zou nooit moeten gebeuren.
		}
		return uniqueInstance;
	}
	
	private Boolean dbExists(String dataSource) {
		Boolean exists = false;
		try{
			Class.forName(driver);
            con = DriverManager.getConnection(dataSource);
           
			exists = true;
		} catch(Exception e){
			; // Do nothing, as DB does not (yet) exist
		}
		return(exists);
	}

	public void close() {
		try {
			con = DriverManager.getConnection(dbname + ";shutdown=true");
		}catch(SQLException se) {
			; // Do Nothing. System has shut down.
		con = null;
		}
	}
	
	public Connection getConnection() {
		return con;
	}
}
